package info.motteke.logger;

import java.util.logging.Level;
import java.util.logging.LogRecord;

/**
 * ログの内容を保持するクラスです。
 *
 * @author YWak
 *
 */
class LogEvent extends LogRecord {

    /**
     *
     */
    private static final long serialVersionUID = 2773585859031410259L;

    private static final String[] IGNORE_PACKAGE = {
        java.util.logging.Logger.class.getPackage().getName(),
        info.motteke.logger.LogEvent.class.getPackage().getName(),
    };

    private transient boolean doGetCallee = true;

    private String sourceClassName = null;

    private String sourceMethodName = null;

    public LogEvent(Level level, String msg) {
        super(level, msg);
    }

    @Override
    public String getSourceClassName(){
        if(doGetCallee){
            getCallee();
        }
        return sourceClassName;
    }

    @Override
    public void setSourceClassName(String sourceClassName){
        this.sourceClassName = sourceClassName;
        doGetCallee = false;
    }

    @Override
    public String getSourceMethodName(){
        if(doGetCallee){
            getCallee();
        }
        return sourceMethodName;
    }

    @Override
    public void setSourceMethodName(String sourceMethodName){
        this.sourceMethodName = sourceMethodName;
        doGetCallee = false;
    }

    private void getCallee(){
        StackTraceElement[] stack = Thread.currentThread().getStackTrace();
        int index = -1;
        // getStackTrace()の分をのぞく。
        for(int i = 1; i < stack.length; i++){
            String p = stack[i].getClassName();
            boolean ignore = false;
            for(String ignorePackage : IGNORE_PACKAGE){
                if(p.startsWith(ignorePackage)){
                    ignore = true;
                    break;
                }
            }
            if(!ignore){
                index = i;
                break;
            }
        }

        if(index >= 0){
            setSourceClassName(stack[index].getClassName());
            setSourceMethodName(stack[index].getMethodName());
        }
        doGetCallee = true;
    }
}
